package cn.wolfcode.job;

import cn.wolfcode.common.web.Result;
import cn.wolfcode.domain.SeckillProductVo;
import cn.wolfcode.feign.SeckillProductFeignApi;
import cn.wolfcode.redis.JobRedisKey;
import com.alibaba.fastjson.JSON;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

//定时
@Component
@Getter
@Setter
public class MyInitSeckillProductJob implements SimpleJob {
    @Autowired
    private SeckillProductFeignApi seckillProductFeignApi;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Value("${jobCron.initSeckillProduct}")
    private String cron;

    @Override
    public void execute(ShardingContext shardingContext) {
        //System.out.println(shardingContext.getShardingParameter());
        dowork(shardingContext.getShardingParameter());
    }

    //time代表不同的秒杀时间
    private void dowork(String time) {
        //1、远程调用秒杀的服务，将数据进行查询出来
        Result<List<SeckillProductVo>> result = seckillProductFeignApi.queryByTime(Integer.parseInt(time));
        /*
        result几种存储形式：
            ①直接在访问秒杀的服务直接挂掉，直接走降级处理
            ②秒杀服务调用没有问题
            ③秒杀服务内部出现问题；直接报秒杀服务繁忙
         */
        //正常的情况下
        if (result != null && !result.hasError()) {
            List<SeckillProductVo> seckillProductVos = result.getData();
            if (seckillProductVos != null && seckillProductVos.size() > 0) {
                //2、将数据查取出来放在redis中
                for (SeckillProductVo seckillProductVo : seckillProductVos) {
                    redisTemplate.opsForHash().put(JobRedisKey.SECKILL_PRODUCT_LIST.getRealKey(time),
                            seckillProductVo.getId() + "", JSON.toJSONString(seckillProductVo));
                    redisTemplate.opsForHash().put(JobRedisKey.SECKILL_STOCK_COUNT_HASH.getRealKey(time),
                            seckillProductVo.getId() + "", seckillProductVo.getStockCount() + "");
                }
                System.out.println("数据同步成功：" + time);
            }
        }

    }
}
